import { defineStore } from 'pinia'
import { LoginService, OpenAPI, UserService } from '/@/api/openapi'
import { ElMessage } from 'element-plus'
import { global } from '/@/config/global'

// 优化状态接口定义
export interface IUserState {
  username: string
  uid: number
  token: string
  isSign: boolean
  avatar: string
}

export const useUserStore = defineStore('user', {
  state: (): IUserState => ({
    username: '',
    uid: 0,
    token: '',
    avatar: '',
    isSign: false,
  }),

  getters: {
    isLoggedIn(): boolean {
      return this.isSign && !!this.token
    },
  },

  actions: {

    getUserId(){
      return this.uid;
    },
    /**
     * 重置用户状态
     */
    resetState() {
      this.username = ''
      this.uid = 0
      this.token = ''
      this.avatar = ''
      this.isSign = false
    },

    /**
     * 登出
     */
    loginOut() {
      OpenAPI.TOKEN = ''
      this.resetState()
      localStorage.removeItem(global.USER)
      localStorage.removeItem(global.USERINFO)
      ElMessage.success('已退出登录')
    },

    /**
     * 初始化用户信息
     */
    initData() {
      const token = localStorage.getItem(global.USER)
      if (token) {
        this.updateToken(token)
        this.updateUser()
      }
    },

    /**
     * 更新Token
     */
    updateToken(token: string) {
      OpenAPI.TOKEN = token
      this.token = token
      localStorage.setItem(global.USER, token)
    },

    /**
     * 更新用户信息
     */
    async updateUser() {
      try {
        const res = await UserService.queryById()
        const userData = res.data

        if (!userData) {
          throw new Error('获取用户信息失败')
        }

        this.isSign = true
        this.username = userData.username || ''
        this.uid = userData.id || 0
        this.avatar = userData.avatar || ''

        localStorage.setItem(global.USERINFO, JSON.stringify(userData))
      } catch (error) {
        console.error('更新用户信息失败:', error)
        ElMessage.error('获取用户信息失败')
        this.loginOut()
      }
    },

    /**
     * 用户登录
     */
    async login(username: string, password: string): Promise<boolean> {
      try {
        const loginData = { username, password }
        const res = await LoginService.login(loginData)

        if (!res.data) {
          throw new Error('登录失败')
        }

        this.updateToken(res.data)
        await this.updateUser()
        return true
      } catch (error) {
        console.error('登录失败:', error)
        ElMessage.error('登录失败，请检查用户名和密码')
        return false
      }
    },
  },
})
